<template>
  <div class="container">
    <div class="app-container">
      <!-- 左上角添加角色按钮 -->
      <div style="padding: 10px">
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 中间列表表格 -->
      <el-table :data="roleList">

        <!-- 第一列 -->
        <el-table-column prop="name" label="角色" align="center" width="200">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <!-- 第二列 -->
        <el-table-column prop="state" label="启用" align="center" width="200">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '启用' : row.state === 0 ? '未启用' : '其他' }}</span>
          </template>
        </el-table-column>

        <!-- 第三列 -->
        <el-table-column prop="description" label="描述" align="center">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" :rows="2" style="width: 400px" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>

        <!-- 第四列 -->
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <div v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="editConfirmClick(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </div>
            <div v-else>
              <el-button type="text" size="mini" @click="permBtnClick(row)">分配权限</el-button>
              <el-button type="text" size="mini" @click="editClick(row)">编辑</el-button>

              <el-popconfirm
                title="您确定删除吗？"
                @onConfirm="delConfirmClick(row)"
              >
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>

      </el-table>

      <el-row style="height: 40px" type="flex" justify="end" align="middle">
        <el-pagination
          layout="prev, pager, next"
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>

    <!-- 弹层组件 -->
    <el-dialog title="新增角色" :visible.sync="showDialog" width="500px" @close="cancelClick">
      <!-- 角色表单 -->
      <el-form ref="roleFrom" label-width="100px" :model="roleFrom" :rules="roleRules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleFrom.name" size="mini" style="width: 300px" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch v-model="roleFrom.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleFrom.description" :rows="3" type="textarea" size="mini" style="width: 300px" />
        </el-form-item>
        <el-form-item>
          <el-row style="width: 300px" type="flex" justify="center">
            <el-button size="mini" type="primary" @click="confirmClick">确定</el-button>
            <el-button size="mini" @click="cancelClick">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限组件 -->
    <el-dialog title="分配权限" :visible.sync="showPermDialog" @close="close">
      <el-tree
        ref="permTree"
        :data="permList"
        :props="{label: 'name'}"
        default-expand-all
        show-checkbox
        check-strictly
        node-key="id"
      />

      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="assignPermConfirmClick">确定</el-button>
          <el-button size="mini" @click="close">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getRolesAPI, addRoleAPI, updateRoleAPI, deleteRoleAPI, getRoleDetailAPI, assignPermAPI } from '@/api/role'
import { tranListToTreeDate } from '@/utils'
import { getPermissionsAPI } from '@/api/permisson'
export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      showDialog: false,
      roleFrom: {
        name: '',
        description: '',
        state: 1
      },
      roleRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      showPermDialog: false,
      permList: [],
      currentId: null
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async assignPermConfirmClick() {
      await assignPermAPI({
        id: this.currentId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.close()
    },
    close() {
      // console.log('弹层关闭')
      this.showPermDialog = false
      this.$refs.permTree.setCheckedKeys([])
    },
    async permBtnClick(row) {
      this.currentId = row.id
      this.showPermDialog = true
      this.permList = tranListToTreeDate(await getPermissionsAPI())
      const { permIds } = await getRoleDetailAPI(row.id)
      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(permIds)
      })
    },
    async getRolesList() {
      const { rows, total } = await getRolesAPI(this.pageParams)
      this.roleList = rows
      this.pageParams.total = total

      this.roleList.forEach(item => {
        this.$set(item, 'isEdit', false)

        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })

      // this.roleList.forEach(item => {

      // })
    },
    // 表格下方分页器  点击下一页或指定的一页就会触发
    // 触发此事件后会修改data的页数 并且重新调用点击页数对应的数据  显示到页面上
    handleCurrentChange(currentPage) {
      this.pageParams.page = currentPage
      this.getRolesList()
    },
    // 点击增加角色里面的确认添加按钮 整体校验 调接口 关闭弹框并清除
    confirmClick() {
      this.$refs.roleFrom.validate(async(isOk) => {
        if (isOk) {
          await addRoleAPI(this.roleFrom)
          this.$message.success('新增角色成功')
          this.getRolesList()
          this.cancelClick()
        }
      })
    },
    // 增加角色里面的取消按钮 关闭弹框并且清空
    cancelClick() {
      this.$refs.roleFrom.resetFields()
      this.showDialog = false
    },
    // 点击编辑按钮 回显
    editClick(row) {
      row.isEdit = true

      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
    },
    // 点击编辑里面的确认按钮  确认修改
    async editConfirmClick(row) {
      // row.isEdit = false

      // row.name = row.editRow.name
      // row.description = row.editRow.description
      // row.state = row.editRow.state

      if (row.editRow.name && row.editRow.description) {
        await updateRoleAPI({ ...row.editRow, id: row.id })
        this.$message.success('修改角色成功')
        Object.assign(row, { ...row.editRow, isEdit: false })
      } else {
        this.$message.error('角色名称和描述不能为空')
      }
    },
    // 点击删除按钮里面的确认
    async delConfirmClick(row) {
      await deleteRoleAPI(row.id)
      this.$message.success('删除角色成功')
      if (this.pageParams.page > 1 && this.roleList.length === 1) {
        this.pageParams.page--
      }
      this.getRolesList()
    }
  }
}
</script>
